<template>
  <div id="app" class="container">
    <h1>Todoist</h1>
    
    <!-- 添加任务区域 -->
    <div class="add-todo-section">
      <input
        v-model="newTodoText"
        @keyup.enter="addTodo"
        placeholder="输入新任务..."
        class="todo-input"
      />
      <button @click="addTodo" class="add-btn" :disabled="!newTodoText.trim() || loading">
        {{ loading ? '添加中...' : '添加任务' }}
      </button>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      <span>❌ {{ error }}</span>
      <button @click="error = ''" class="close-error">×</button>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <input
        v-model="searchQuery"
        placeholder="🔍 搜索任务..."
        class="search-input"
      />
      <div class="filter-buttons">
        <button 
          @click="currentFilter = 'all'"
          :class="{ active: currentFilter === 'all' }"
          class="filter-btn"
        >
          全部 ({{ todos.length }})
        </button>
        <button 
          @click="currentFilter = 'active'"
          :class="{ active: currentFilter === 'active' }"
          class="filter-btn"
        >
          未完成 ({{ activeTodos.length }})
        </button>
        <button 
          @click="currentFilter = 'completed'"
          :class="{ active: currentFilter === 'completed' }"
          class="filter-btn"
        >
          已完成 ({{ completedTodos.length }})
        </button>
      </div>
    </div>

    <!-- 任务列表 -->
    <div class="todo-list">
      <!-- 加载状态 -->
      <div v-if="loading && todos.length === 0" class="loading-state">
        <div class="loading-spinner"></div>
        <p>正在加载任务...</p>
      </div>
      
      <TransitionGroup v-else name="todo" tag="div">
        <div
          v-for="todo in filteredTodos"
          :key="todo.id"
          :class="['todo-item', { completed: todo.completed }]"
        >
          <input
            type="checkbox"
            :checked="todo.completed"
            @change="toggleTodo(todo)"
            class="todo-checkbox"
          />
          <div class="todo-content">
            <div class="todo-text">{{ todo.text }}</div>
            <div class="todo-dates">
              <span class="created-date">
                📅 创建: {{ formatDate(todo.createdAt) }}
              </span>
              <span v-if="todo.completed && todo.completedAt" class="completed-date">
                ✅ 完成: {{ formatDate(todo.completedAt) }}
              </span>
            </div>
          </div>
          <button @click="deleteTodo(todo.id)" class="delete-btn" title="删除任务">
            🗑️
          </button>
        </div>
      </TransitionGroup>
    </div>

    <!-- 空状态提示 -->
    <div v-if="filteredTodos.length === 0" class="empty-state">
      <div class="empty-icon">📝</div>
      <p v-if="searchQuery">没有找到匹配 "{{ searchQuery }}" 的任务</p>
      <p v-else-if="currentFilter === 'active'">🎉 暂无未完成任务！</p>
      <p v-else-if="currentFilter === 'completed'">暂无已完成任务</p>
      <p v-else>暂无任务，添加一个开始吧！</p>
    </div>

    <!-- 统计信息和操作 -->
    <div class="footer" v-if="todos.length > 0">
      <div class="stats">
        <span class="stat-item">📊 总任务: {{ todos.length }}</span>
        <span class="stat-item">✅ 已完成: {{ completedTodos.length }}</span>
        <span class="stat-item">⏳ 未完成: {{ activeTodos.length }}</span>
      </div>
      <div class="actions" v-if="completedTodos.length > 0">
        <button @click="clearCompleted" class="clear-btn">
          清除已完成任务
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { invoke } from '@tauri-apps/api/core'

// 响应式数据
const newTodoText = ref('')
const searchQuery = ref('')
const currentFilter = ref('all')
const todos = ref([])
const loading = ref(false)
const error = ref('')

// 计算属性
const activeTodos = computed(() => todos.value.filter(todo => !todo.completed))
const completedTodos = computed(() => todos.value.filter(todo => todo.completed))

const filteredTodos = computed(() => {
  let filtered = todos.value

  // 根据搜索查询过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(todo =>
      todo.text.toLowerCase().includes(query)
    )
  }

  // 根据完成状态过滤
  if (currentFilter.value === 'active') {
    filtered = filtered.filter(todo => !todo.completed)
  } else if (currentFilter.value === 'completed') {
    filtered = filtered.filter(todo => todo.completed)
  }

  // 按创建时间倒序排列
  return filtered.sort((a, b) => {
    if (currentFilter.value === 'completed' && a.completedAt && b.completedAt) {
      // 已完成任务按完成时间倒序
      return new Date(b.completedAt) - new Date(a.completedAt)
    }
    return new Date(b.createdAt) - new Date(a.createdAt)
  })
})


// 安全的UTC时间转换函数
const parseUTCDate = (dateString) => {
  if (!dateString || dateString === null) return null
  try {
    let date
    // 处理不同的时间格式
    if (dateString.includes('T') && dateString.includes('+')) {
      // ISO格式带时区: 2025-07-29T13:30:39.919116700+00:00
      date = new Date(dateString)
    } else if (dateString.includes('T')) {
      // ISO格式无时区: 2025-07-29T13:30:39
      date = new Date(dateString + 'Z')
    } else {
      // SQLite默认格式: 2025-07-29 12:17:38
      date = new Date(dateString + 'Z')
    }
    return isNaN(date.getTime()) ? null : date
  } catch (err) {
    console.error('时间解析失败:', dateString, err)
    return null
  }
}

// 加载所有任务
const loadTodos = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const data = await invoke('get_todos', { 
      searchFilter: { 
        search: searchQuery.value || null, 
        filter: currentFilter.value === 'all' ? null : currentFilter.value 
      } 
    })
    todos.value = data.map(todo => ({
      ...todo,
      createdAt: parseUTCDate(todo.created_at),
      completedAt: parseUTCDate(todo.completed_at)
    }))
  } catch (err) {
    console.error('加载任务失败:', err)
    error.value = err
  } finally {
    loading.value = false
  }
}

// 添加任务
const addTodo = async () => {
  const text = newTodoText.value.trim()
  if (!text) return
  
  loading.value = true
  error.value = ''
  
  try {
    const newTodo = await invoke('create_todo', { text })
    
    // 转换日期格式并添加到列表顶部
    const formattedTodo = {
      ...newTodo,
      createdAt: parseUTCDate(newTodo.created_at),
      completedAt: parseUTCDate(newTodo.completed_at)
    }
    
    todos.value.unshift(formattedTodo)
    newTodoText.value = ''
  } catch (err) {
    console.error('添加任务失败:', err)
    error.value = err
  } finally {
    loading.value = false
  }
}

// 切换任务状态
const toggleTodo = async (todo) => {
  const originalCompleted = todo.completed
  
  // 乐观更新
  todo.completed = !todo.completed
  if (todo.completed) {
    todo.completedAt = new Date()
  } else {
    todo.completedAt = null
  }
  
  try {
    const updatedTodo = await invoke('update_todo_status', {
      payload: { id: todo.id, completed: todo.completed }
    })
    
    // 更新任务数据
    const index = todos.value.findIndex(t => t.id === todo.id)
    if (index > -1) {
      todos.value[index] = {
        ...updatedTodo,
        createdAt: parseUTCDate(updatedTodo.created_at),
        completedAt: parseUTCDate(updatedTodo.completed_at)
      }
    }
  } catch (err) {
    // 回滚更改
    todo.completed = originalCompleted
    if (originalCompleted) {
      todo.completedAt = new Date()
    } else {
      todo.completedAt = null
    }
    console.error('更新任务失败:', err)
    error.value = err
  }
}

// 删除任务
const deleteTodo = async (id) => {
  if (!confirm('确定要删除这个任务吗？')) return
  
  const originalTodos = [...todos.value]
  
  // 乐观删除
  todos.value = todos.value.filter(todo => todo.id !== id)
  
  try {
    await invoke('delete_todo', { id })
  } catch (err) {
    // 回滚删除
    todos.value = originalTodos
    console.error('删除任务失败:', err)
    error.value = err
  }
}

// 清除已完成任务
const clearCompleted = async () => {
  if (!confirm('确定要清除所有已完成的任务吗？')) return
  
  const originalTodos = [...todos.value]
  
  // 乐观删除
  todos.value = todos.value.filter(todo => !todo.completed)
  
  try {
    await invoke('delete_completed_todos')
  } catch (err) {
    // 回滚删除
    todos.value = originalTodos
    console.error('清除已完成任务失败:', err)
    error.value = err
  }
}

const formatDate = (date) => {
  if (!date) return ''
  
  const now = new Date()
  let taskDate = new Date(date)
  
  // 调试日志
  console.log('Formatting date:', date, 'Now:', now, 'TaskDate:', taskDate)
  
  // 计算时间差
  const diffMs = now - taskDate
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)

  if (diffMins < 1) return '刚刚'
  if (diffMins < 60) return `${diffMins} 分钟前`
  if (diffHours < 24 && diffDays === 0) return `${diffHours} 小时前`
  if (diffDays === 1) return '昨天'
  if (diffDays < 7) return `${diffDays} 天前`

  return taskDate.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  })
}

// 生命周期
onMounted(() => {
  loadTodos()
})

// 监听搜索和筛选变化
watch([searchQuery, currentFilter], () => {
  // 在实际应用中，这里可以实现服务端搜索和筛选
  // 目前使用客户端筛选
}, { immediate: false })

// 键盘快捷键
onMounted(() => {
  const handleKeydown = (e) => {
    // Ctrl/Cmd + K 聚焦搜索框
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
      e.preventDefault()
      document.querySelector('.search-input')?.focus()
    }
  }
  document.addEventListener('keydown', handleKeydown)
  
  // 清理事件监听器
  onUnmounted(() => {
    document.removeEventListener('keydown', handleKeydown)
  })
})
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-attachment: fixed;
}

h1 {
  text-align: center;
  color: white;
  margin-bottom: 30px;
  font-size: 2.5rem;
  font-weight: 300;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

/* 添加任务区域 */
.add-todo-section {
  display: flex;
  gap: 10px;
  margin-bottom: 25px;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.todo-input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.todo-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.add-btn {
  padding: 15px 25px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.add-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.add-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 错误提示 */
.error-message {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fee;
  border: 1px solid #fcc;
  color: #c33;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  animation: slideIn 0.3s ease;
}

.close-error {
  background: none;
  border: none;
  color: #c33;
  font-size: 20px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-error:hover {
  background: rgba(204, 51, 51, 0.1);
  border-radius: 4px;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 40px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 搜索和筛选区域 */
.filter-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.search-input {
  width: 95%;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 16px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.filter-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-btn {
  padding: 10px 20px;
  border: 2px solid #e1e5e9;
  background: white;
  border-radius: 25px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.filter-btn.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: transparent;
}

.filter-btn:hover:not(.active) {
  border-color: #667eea;
  transform: translateY(-1px);
}

/* 任务列表 */
.todo-list {
  margin-bottom: 20px;
}

.todo-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.todo-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.todo-item.completed {
  opacity: 0.8;
  background: #f8f9fa;
}

.todo-checkbox {
  width: 22px;
  height: 22px;
  margin-top: 2px;
  cursor: pointer;
  accent-color: #667eea;
}

.todo-content {
  flex: 1;
}

.todo-text {
  font-size: 16px;
  line-height: 1.5;
  margin-bottom: 8px;
  color: #2c3e50;
}

.completed .todo-text {
  text-decoration: line-through;
  color: #7f8c8d;
}

.todo-dates {
  font-size: 13px;
  color: #7f8c8d;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.completed-date {
  color: #27ae60;
  font-weight: 600;
}

.delete-btn {
  padding: 8px 12px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  background: #c0392b;
  transform: scale(1.1);
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 20px;
}

.empty-state p {
  color: #7f8c8d;
  font-size: 18px;
  font-style: italic;
}

/* 底部统计和操作 */
.footer {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.stats {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.stat-item {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.actions {
  text-align: center;
}

.clear-btn {
  padding: 10px 20px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s ease;
}

.clear-btn:hover {
  background: #c0392b;
  transform: translateY(-1px);
}

/* 动画效果 */
.todo-enter-active,
.todo-leave-active {
  transition: all 0.5s ease;
}

.todo-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.todo-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

.todo-move {
  transition: transform 0.5s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 15px;
  }
  
  h1 {
    font-size: 2rem;
  }
  
  .add-todo-section {
    flex-direction: column;
    padding: 15px;
  }
  
  .filter-buttons {
    justify-content: center;
  }
  
  .filter-btn {
    flex: 1;
    min-width: 0;
  }
  
  .todo-item {
    padding: 15px;
  }
  
  .todo-dates {
    flex-direction: column;
    gap: 5px;
  }
  
  .stats {
    flex-direction: column;
    gap: 10px;
  }
}

@media (max-width: 480px) {
  .container {
    padding: 10px;
  }
  
  .add-todo-section,
  .filter-section {
    padding: 15px;
  }
  
  .todo-item {
    padding: 12px;
  }
}
</style>